import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _inherits from "@babel/runtime/helpers/esm/inherits";
import _createSuper from "@babel/runtime/helpers/esm/createSuper";

/**
 * 监听 favicon 的 修改, 监听到后, 刷新 header/meta 信息
 * TODO: 是否修改为 公共的更新修改 header/meta 信息 组件
 */
import React from 'react';
import { connect } from 'dva';
var iconElement;
/**
 * 更新 favicon
 */

function updateFavicon(favicon) {
  if (favicon) {
    if (!iconElement) {
      iconElement = document.querySelector('head > link[rel="shortcut icon"]');
    }

    if (!iconElement) {
      // 1
      var linkTag = document.createElement('link');
      linkTag.href = "".concat((process.env.PUBLIC_URL || '').replace(/\/$/, ''), "/favicon.ico");
      linkTag.setAttribute('rel', 'shortcut icon');
      document.getElementsByTagName('head')[0].append(linkTag); // 2

      var headHTML = document.getElementsByTagName('head')[0].innerHTML;
      headHTML += "<link rel=\"shortcut icon\" href=\"".concat((process.env.PUBLIC_URL || '').replace(/\/$/, ''), "/favicon.ico\" />");
      document.getElementsByTagName('head')[0].innerHTML = headHTML;
    }

    if (iconElement && iconElement.href !== favicon) {
      var img = new Image();

      img.onload = function () {
        iconElement.href = favicon;
      };

      img.src = favicon;
    }
  }
}

var DefaultListenFavicon = /*#__PURE__*/function (_React$PureComponent) {
  _inherits(DefaultListenFavicon, _React$PureComponent);

  var _super = _createSuper(DefaultListenFavicon);

  function DefaultListenFavicon(props) {
    var _this;

    _classCallCheck(this, DefaultListenFavicon);

    _this = _super.call(this, props);
    _this.state = {};
    return _this;
  }

  _createClass(DefaultListenFavicon, [{
    key: "render",
    value: function render() {
      return null;
    }
  }], [{
    key: "getDerivedStateFromProps",
    value: function getDerivedStateFromProps(nextProps) {
      updateFavicon(nextProps.favicon);
      return null;
    }
  }]);

  return DefaultListenFavicon;
}(React.PureComponent);

export default connect(function (_ref) {
  var _ref$user = _ref.user,
      user = _ref$user === void 0 ? {} : _ref$user;
  return {
    favicon: (user.currentUser || {}).favicon
  };
})(DefaultListenFavicon);